package xyz.riceball.context;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * <p>
 * 目前只支持加载一个配置文件
 * </p>
 *
 * @author xiaovcloud
 * @since 2021/6/29 21:54
 */
public class ClassPathPropertiesApplicationContext extends AbstractApplicationContext {

    private final Logger log = LoggerFactory.getLogger(getClass());
    /**
     * 默认读取pack
     */
    private static final String DEFAULT_PACK_KEY = "basePack";


    /**
     * 启动容器
     *
     * @param configLocation 文件名称
     */
    public ClassPathPropertiesApplicationContext(String configLocation) {
        super(doParse(configLocation));
        if (configLocation == null) {
            log.error("配置地址不能为空");
        }
    }

    /**
     * 解析文件
     *
     * @param configLocation 文件名
     * @return 包路径
     */
    private static String[] doParse(String configLocation) {
        return doParse(configLocation, DEFAULT_PACK_KEY);
    }

    /**
     * 解析文件
     *
     * @param configLocation 文件名
     * @param pack           扫描的包名key
     * @return 包路径
     */
    private static String[] doParse(String configLocation, String pack) {
        Properties prop = new Properties();
        InputStream inputStream = ClassPathPropertiesApplicationContext.class
                .getClassLoader().getResourceAsStream(configLocation);
        try {
            prop.load(inputStream);
            String packs = (String) prop.get(pack);
            if (packs == null) {
                //没有找到basePackages
                throw new RuntimeException("没有找到关于【" + pack + "】的配置信息");
            }
            return packs.split(",");
        } catch (IOException e) {
            throw new RuntimeException("未解析到正确的properties文件", e);
        }
    }
}
